// 把这些玩意儿放在mod里面的好处在于非常容易编写测试
use std::fs;
use std::env;
use std::error::Error;

// Box意味着会返回实现了Error trait的类型
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {

    // as long as you need read file to string,you can use "?"
    let contents = fs::read_to_string(config.filename)?;

    // &String can be passed to parameter which type is &str , but String can't passed.
    let results= if config.case_sensitive {
        search_case_sensitive(&config.query,&contents)
    } else {
        println!("{}","INSENSITIVE!");
        search_case_insensitive(&config.query, &contents)
    };



    for line in results {
        println!("{}",line);
    }


    Ok(()) // 这只是副作用,因为我们想要一个Result的返回值但实际上我们只是因为这是Rust错误处理的手段
    // 我们现在想要的其实仅仅是这个Result里面的Err,所以如果正确,调用方只会得到()
}

pub struct Config {
    pub query: String,
    pub filename: String,
    pub case_sensitive:bool
}

// 把用到的数据组合在Config里
// 错误检查放在new里,如果生成结构体失败那么就返回Err(e)
impl Config {
    pub fn new(args: &[String]) -> Result<Config, &'static str> {
        if args.len() !=3 {
            return Err("parameter error");
        }

        let query = args[1].clone();
        let filename = args[2].clone();

        let case_sensitive = env::var("CASE_INSENSITIVE").is_err();

        Ok(Config { query, filename ,case_sensitive})
    }
}

// 我们在一开始就要想清楚,返回值&str正是contents的slice引用,
// 所以要在生命周期上将这一点反映出来

fn search_case_sensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut result = Vec::new();
    for line in contents.lines() {
        if line.contains(query) {
            result.push(line);
        }
    }
    result
}


fn search_case_insensitive<'a> (query:&str,contents:&'a str)->Vec<&'a str> {
    let query = query.to_lowercase();
    let mut result = Vec::new();
    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            result.push(line);
        }
    }

    result
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "Rust:\nsafe,fast,productive.\nPick three.\nDuct tape.";
        assert_eq!(
            search_case_sensitive(query, contents),
            vec!["safe,fast,productive."]
        )
    }

    #[test]
    fn case_insensitive() {
        let query = "rUst";
        let contents = "Rust:\nsafe,fast,productive.\nPick three.\nTrust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}